import 'package:flutter/material.dart';
import 'package:sharing/resources/styles.dart';
import 'package:sharing/resources/colors.dart';
import 'package:sharing/resources/dimens.dart';
import 'package:sharing/ui/login_register_header.dart';
import 'package:sharing/ui/widget/user_register.dart';
import 'package:sharing/net/net_util.dart';
import 'package:sharing/utils/whole_apis.dart';
import 'package:sharing/model/login.dart';
import 'package:sharing/model/res_msg.dart';
import 'package:dio/dio.dart';
import 'dart:convert';
import 'my_app.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Login extends StatefulWidget {
  static const String regPhone =
      '^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}\$';

  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  String _pwd = "";
  String _phone = "";

  _login() async {
    NetUtil.post(WholeApis.loginUrl, (String data) {
      // print("response  "+data);
      var _data = json.decode(data);
      var _resmsg = ResMsg.fromJson(_data);
      print("${_resmsg} ");

      if(_resmsg .authorization != null){
       _setAuthorization(_resmsg .authorization);
      }
    }, params: {"phone": _phone, "pass_word": _pwd});
  }

  _setAuthorization(String auth) async{
    SharedPreferences prefs = await SharedPreferences.getInstance();

    await prefs.setString('authorization', auth);
    Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (get) =>MyApp()),  (Route route) => route == null);
  }
  @override
  Widget build(BuildContext context) {
    return Material(
      child: Scaffold(
        body: Stack(
          fit: StackFit.expand,
          children: <Widget>[
            Column(
              children: <Widget>[
                SizedBox(
                  height: Dimensions.pd48,
                ),

                // 构建头部的提示文字
                LoginOrRegisterHeader(
                  text: "登录",
                ),
                _buildPhoneField(context),
                _buildPassword(context),

                // 空格 注册按钮和 密码输入框
                SizedBox(
                  height: Dimensions.pd32,
                ),
                _LoginBtn(
                  onText: _callbackLogin,
                ),
              ],
            ),
            Container(
              alignment: Alignment.bottomCenter,
              margin: const EdgeInsets.only(bottom: Dimensions.pd8),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    "登录有问题",
                    style: TextStyle(
                      color: AppColor.primary,
                      fontSize: Dimensions.fontSp10,
                      fontWeight: FontWeight.normal,
                    ),
                  ),
                  SizedBox(
                    width: Dimensions.pdSixteen,
                  ),
                  Text("|"),
                  SizedBox(
                    width: Dimensions.pdSixteen,
                  ),
                  GestureDetector(
                    onTap: () {
                      Navigator.of(context).pushReplacement(
                          MaterialPageRoute(builder: (context) => Register()));
                    },
                    child: Text(
                      "注册",
                      style: TextStyle(
                          color: AppColor.primary,
                          fontSize: Dimensions.fontSp10,
                          fontWeight: FontWeight.normal),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构造手机号码的输入域
  Widget _buildPhoneField(BuildContext context) {
    return new Container(
      //  color: Colors.orange,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: TextField(
     //  autofocus: true ,
       maxLength: Dimensions.phoneInput,
       keyboardType: TextInputType.number,
        style: TextStyle(
          fontSize: Dimensions.fontSp20,
          color: Colors.black,
          fontWeight: FontWeight.normal,
        ),
        decoration: InputDecoration(
          contentPadding: EdgeInsets.all(Dimensions.pd10),
          prefixIcon: Icon(Icons.phone_android),
          labelText: '请输入您的手机号码..',
          labelStyle: TextStyle(
              fontSize: Dimensions.fontSp14,
              color: Colors.black54,
              fontWeight: FontWeight.normal),
          helperText: '',
        ),
       onChanged: _phoneInputChanged,
       textInputAction: TextInputAction.next,
        autofocus: true,
        onSubmitted: (Str) {
          // print("submit ${Str}");
        },
      ),
    );
  }

  // 构造密码的输入域
  Widget _buildPassword(BuildContext context) {
    return new Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: TextField(
        keyboardType: TextInputType.text,
        maxLength: Dimensions.pwdInput,
        // 长度16 个字符输入
        decoration: InputDecoration(
          contentPadding: EdgeInsets.all(Dimensions.pd10),
          prefixIcon: Icon(Icons.fingerprint),
          labelText: '请输入您的密码',
          labelStyle: TextStyle(
              fontSize: Dimensions.fontSp14,
              color: Colors.black54,
              fontWeight: FontWeight.normal),
          helperText: '密码的长度不小于8',
          helperStyle: TextStyle(
              fontSize: Dimensions.fontSp10,
              color: Colors.grey,
              fontWeight: FontWeight.normal),
        ),
        obscureText: true,
        // 密码输入
        onChanged: _pwdInputChanged,
        textInputAction: TextInputAction.next,

        // autofocus: true,
      ),
    );
  }

  // 密码输入
  void _pwdInputChanged(String value) {
    _pwd = value;
  }

  // 手机号码输入
  void _phoneInputChanged(String value) {
    _phone = value;
  }

  // 登录的回调接口
  void _callbackLogin() {
    // 判断手机号码
    bool ok = regValid(Login.regPhone, _phone);
    // 判断密码
    bool opw = _pwd.length >= 8 && _pwd.length < 16;
    if (!ok || !opw) {
      print("手机号码不正确 ${_phone}  或者密码不正确 ${_pwd}");

      return;
    }

    _login();

    print("   ${_phone}   ${_pwd}");
  }

  // 正则匹配手机号码
  bool regValid(String patten, String str) {
    return new RegExp(patten).hasMatch(str);
  }
}

class _LoginBtn extends StatefulWidget {
  String _inputPhone;

  VoidCallback onText;

  _LoginBtn({Key key, @required this.onText}) : super(key: key);

  @override
  __LoginBtnState createState() => __LoginBtnState();
}

class __LoginBtnState extends State<_LoginBtn> {
  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Expanded(
          child: GestureDetector(
            onTap: () {
              widget.onText();
              Scaffold.of(context).showSnackBar(SnackBar(
                content: Text(
                  "点击的登录事件 ${widget._inputPhone}",
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: Dimensions.fontSp12,
                    color: Colors.black,
                  ),
                ),
                duration: Duration(seconds: 2),
                backgroundColor: Colors.white,
              ));
            },
            child: Container(
              margin: const EdgeInsets.all(Dimensions.pd8),
              padding: const EdgeInsets.symmetric(vertical: Dimensions.pd8),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(Dimensions.pd8),
                color: AppColor.primary,
              ),
              alignment: Alignment.center,
              child: Text(
                "登录",
                style: TextStyle(
                    fontSize: Dimensions.fontSp20,
                    color: Colors.white,
                    fontWeight: FontWeight.normal),
              ),
            ),
          ),
        )
      ],
    );
  }
}
